package org.item.auth.controller;

import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.item.common.bean.SysPermission;
import org.item.common.bean.SysRole;
import org.item.common.bean.SysUser;
import org.item.common.exception.ParameterException;
import org.item.common.service.IRedisService;
import org.item.common.service.IUserService;
import org.item.common.util.JWTUtil;
import org.item.common.util.PasswordDecode;
import org.item.common.util.ResultData;
import org.item.common.util.SYSUtil;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("auth")
@CrossOrigin
public class AuthController {
    @DubboReference
    IUserService userService;
    @DubboReference
    IRedisService redisService;
    @PostMapping("/login")
    public ResultData login(@RequestBody SysUser user) {
        //获取用户名和密码
        String username = user.getUsername();
        String password = user.getPassword();

        System.out.println("收到的用户名：" + user.getUsername());
        System.out.println("收到的密码：" + user.getPassword());
        SysUser sysUser;
        if (!SYSUtil.checkEmpty(username, password)) {
            //通过用户名获取用户数据
            sysUser = userService.getByUsername(username);
            if (SYSUtil.checkNull(sysUser)) {
                //比较密码
                String password_data = sysUser.getPassword();
                if (PasswordDecode.decode(password, password_data)) {
                    //如果签发成功
                    String token = JWTUtil.generateToken(null);
                    String allPermission = getAllPermission(sysUser);
                    redisService.set(token, allPermission);
                    return ResultData.success(token);
                } else {
                    throw new RuntimeException("密码不正确");
                }
            } else {
                throw new RuntimeException("没有此账号");
            }
            //访问user
        } else {
            throw new ParameterException("参数错误");
        }
        //验证参数
        //通过用户名获取用户数据
        //验证密码是否正确
        //返回对应结果

    }
    private String getAllPermission(SysUser user) {
        StringBuilder strb = new StringBuilder();
        for (SysRole role : user.getRoles()) {
            strb.append(role.getRolekey());
            strb.append(",");
            for (SysPermission permission : role.getPermissions()) {
                strb.append(permission.getPermkey());
                strb.append(",");
            }
        }
        return strb.toString();
    }


}
